package com.leetcode.leetcode1;

import java.util.Arrays;

/**
 *  最接近的三数之和
 * @author: luhd
 * @create: 2021-08-26
 */
public class Practice16 {
    public static void main(String[] args) {
        int[] nums = { -1,2,1,-4};
        int target = 1;
        int i = threeSumClosest(nums, target);
        System.out.println(i);
    }
    public static int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        int ans = Integer.MAX_VALUE;
        int res = 0;
        Arrays.sort(nums);
        for (int i = 0; i < len - 2; i++) {
            for (int j = i+1; j < len - 1; j++) {
                for (int k = j+1; k < len; k++) {
                    if(Math.abs(nums[i]+nums[j]+nums[k]-target)<ans){
                        ans = Math.abs(nums[i]+nums[j]+nums[k]-target);
                        res = nums[i]+nums[j]+nums[k];
                    }
                }
            }
        }
        return res;
    }
}
